﻿using KqAutoDesign.Base;
using KqAutoDesign.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip;

namespace KqAutoDesign.SonViews
{
    /// <summary>
    /// WorkFlowSettingUc.xaml 的交互逻辑
    /// </summary>
    public partial class WorkFlowSettingUc : UserControl, INotifyPropertyChanged
    {
        public WorkFlowSettingUc()
        {
            InitializeComponent();
            wfUc.WorkflowSaved += WfUc_WorkflowSaved;
            DataContext = this;
        }

        private void WfUc_WorkflowSaved()
        {
            var cloned = wfUc.Wfb.Clone();
            var oldOne = WorkFlows.FirstOrDefault(x => x.Id == wfUc.Wfb.Id);
            var oldid = WorkFlows.IndexOf(oldOne);
            WorkFlows.RemoveAt(oldid);
            WorkFlows.Insert(oldid, cloned);
            SelectedWorkflow = cloned;
            GlobalConfigXMLManager globalConfigXMLManager = new GlobalConfigXMLManager();
            globalConfigXMLManager.AddWorkflow(cloned);
            SaveScripts(cloned);
        }

        private void SaveScripts(WorkFlowBase cloned)
        {
            if (cloned == null||cloned.Modules==null|| cloned.Modules.Count<=0)
                return;
            string workflowFolder = App.GlobalConfigs.WorkflowFolderPath + cloned.Name;
            if (!Directory.Exists(workflowFolder))
                Directory.CreateDirectory(workflowFolder);
            List<string> needFiles = new List<string>();
            foreach (var md in cloned.Modules)
            {
                if(!string.IsNullOrEmpty(md.BatchScript.OrgFilePath))
                {
                    string desFile = workflowFolder + "\\" + md.BatchScript.FileName;
                    File.Copy(md.BatchScript.OrgFilePath, desFile, true);
                    needFiles.Add(desFile);
                }
                    
                foreach (var fs in md.FunctionScripts)
                {
                    if(!string.IsNullOrEmpty(fs.OrgFilePath))
                    {
                        string desFile = workflowFolder + "\\" + fs.FileName;
                        File.Copy(fs.OrgFilePath, desFile, true);
                        needFiles.Add(desFile);
                    }
                }
            }
            string[] allFiles = Directory.GetFiles(workflowFolder, "*.*", SearchOption.AllDirectories);
            foreach (var file in allFiles)
            {
                if(!needFiles.Contains(file)&&File.Exists(file))
                    File.Delete(file);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        public ObservableCollection<WorkFlowBase> WorkFlows
        {
            get { return App.GlobalConfigs.WorkFlowTemplates; }
            set
            {
                App.GlobalConfigs.WorkFlowTemplates = value;
                RaisePropertyChanged(nameof(WorkFlows));
            }
        }

        private WorkFlowBase _selectedWorkflow;
        public WorkFlowBase SelectedWorkflow
        {
            get => _selectedWorkflow;
            set
            {
                if (_selectedWorkflow != value)
                {
                    _selectedWorkflow = value;
                    var cloned = _selectedWorkflow?.Clone();
                    if(cloned != null&&cloned.Modules!=null) 
                        cloned.Modules = new ObservableCollection<ModuleBase>(cloned.Modules.OrderBy(x => x.Id));
                    wfUc.Wfb = cloned;
                    RaisePropertyChanged(nameof(SelectedWorkflow));
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<string> existWfNames = new List<string>();
            int id = 0;
            if(WorkFlows!=null)
            {
                foreach (var wf in WorkFlows)
                {
                    existWfNames.Add(wf.Name);
                }
                if(WorkFlows.Count > 0)
                    id = WorkFlows.Max(x=>x.Id);
                else
                    id = 1;
            }
            
            NewWorkflow newWorkflowDlg = new NewWorkflow(++id, existWfNames);
            if(newWorkflowDlg.ShowDialog()==true)
            {
                var baseWf = WorkFlows.FirstOrDefault(x => x.Name == newWorkflowDlg.BaseWfName);
                if(baseWf != null)
                {
                    var cloned = baseWf.Clone();
                    cloned.Name = newWorkflowDlg.Workflow.Name;
                    cloned.Description = newWorkflowDlg.Workflow.Description;
                    cloned.Id = newWorkflowDlg.Workflow.Id;
                    WorkFlows.Add(cloned);
                    string sourceFolder = App.GlobalConfigs.WorkflowFolderPath + baseWf.Name;
                    string destFolder = App.GlobalConfigs.WorkflowFolderPath + cloned.Name;
                    Tools.CopyDirectory(sourceFolder, destFolder);
                }
                else
                {
                    string destFolder = App.GlobalConfigs.WorkflowFolderPath + newWorkflowDlg.Workflow.Name;
                    WorkFlows.Add(newWorkflowDlg.Workflow);
                    if(!Directory.Exists(destFolder))
                        Directory.CreateDirectory(destFolder);
                }
            }
        }

        private void DeleteAction(object sender, RoutedEventArgs e)
        {
            if(SelectedWorkflow!= null)
            {
                if(MessageBox.Show("是否要删除该工作流？","提示",MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    string id = SelectedWorkflow.Id.ToString();
                    string name = SelectedWorkflow.Name;
                    WorkFlows.Remove(SelectedWorkflow);//更新UI
                    GlobalConfigXMLManager globalConfigXMLManager = new GlobalConfigXMLManager();
                    globalConfigXMLManager.DeleteWorkflow(id, name);//删除XML中对应Workflow节点
                    Directory.Delete(App.GlobalConfigs.WorkflowFolderPath + name, true);//删除文件夹
                }
            }
        }
    }
}
